//create by 2017年10月4日16:36:45 lwy


var ifComment = 'false';
var ifSlide = 'true';
var ifDetail = 'false';
var topHeight = 44;
var getHeight = '';
var collectionsId = '';
var token = getItem('token');
var userId = GetQueryString('userId');
var ifChoose = 0;
if(userId==null||userId==undefined||userId==""){}else{
    setItem('userId')
}
var liHeight = $('body').width()*0.31-22;
$(function () {
    doGoods();
    doPrice();
    doComment();
    doCommentList();
    guess();
})
var xData = [],
    yData = [],
    priceSpecificationId = '';

//价格走势
function doPrice() {
    $.ajax({
        url: '/ddmGoodsC/getPriceRecord.json',
        dataType: 'json',
        data: {
            goodsId: goodsId,
            specificationId: priceSpecificationId,
            companyCode:getItem('companyCode'),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                xData = [];
                yData = [];
                var dataData = data.datas.date;
                for (var i = 0; i < dataData.length; i++) {
                    xData.push(dataData[i]);
                }
                var priceData = data.datas.price;
                for (var k = 0; k < priceData.length; k++) {
                    yData.push(priceData[k]);
                }
                doPriceTrend();
            }
        }
    })
}

function doPriceTrend() {
    // 基于准备好的dom，初始化echarts实例
    var myChart = echarts.init(document.getElementById('main'));
// 使用刚指定的配置项和数据显示图表。

// 指定图表的配置项和数据
    option = {
        title: {
            text: 'iphone8 国行版 64GB 银色',
            left: 'center',
        },
        tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c}'
        },
        xAxis: {
            type: 'category',
            name: '日期',
            splitLine: {
                show: false,
            },
            data: xData,
            axisLabel: {
                interval: 0,//横轴信息全部显示
            }
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        yAxis: {
            type: 'value',
            name: '价格',
            splitLine: {
                lineStyle: {
                    color: '#f8f8f8',
                    width: 1
                }
            }
        },
        series: [
            {
                type: 'line',
                itemStyle: {
                    normal: {
                        color: '#1cc7cf',
                        lineStyle: {
                            width: 2,
                            color: '#1cc7ce',
                            background: '#1cc7ce',
                        },
                    },
                },
                symbol: 'circle',
                symbolSize: 7,
                data: yData,
                axisLabel: {
                    interval: 0,//横轴信息全部显示
                }
            },
        ]
    };

    myChart.setOption(option);
}


var goodsId = GetQueryString('goodsId');
var specification;
var isValueAddedServices;

//商品详情
function doGoods() {
    $.ajax({
        url: '/ddmGoodsC/portalDetails.json',
        dataType: 'json',
        data: {
            id: goodsId,
            token: token,
            companyCode:getItem('companyCode'),
        },
        type: 'post',
        beforeSend:function(){
            $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
        },
        success: function (data) {
            $('.loading2').hide();
            if (data.code == 1) {
                var goodsData = data.datas;
                var mainImg = data.datas.mainImg.split(',');
                if(mainImg.length>1){
                    for(var n=0;n<mainImg.length-1;n++){
                        $('<div class="swiper-slide">'+
                            '<a class="banner">'+
                            '<img src="'+mainImg[n]+'">'+
                            '</a></div>').appendTo($('#banner'));
                    }
                }else{
                    for(var n=0;n<mainImg.length;n++){
                        $('<div class="swiper-slide">'+
                            '<a class="banner">'+
                            '<img src="'+mainImg[n]+'">'+
                            '</a></div>').appendTo($('#banner'));
                    }
                }

                $('#spe_img').attr('src', mainImg[0]);
                //轮播图
                var mySwiper = new Swiper ('.swiper-container4', {
                    loop: false,
                    autoplay: 5000,
                    pagination: '.swiper-pagination4',
                    paginationClickable: true,
                })
                specification = goodsData.isSpecification;
                collectionsId = goodsData.collectionsId;
                if (goodsData.isCollections) {
                    $('#collection_img').attr('src', '../phoneImg/collection_act.png');
                    $('#collText').html('已收藏');
                }
                $(goodsData.detailsImg).appendTo($('#detailBox1'));
                doSpe();
                isValueAddedServices = goodsData.isValueAddedServices;
                if (isValueAddedServices) {
                    $('.appreciation_title').show();
                    doService();
                }
                if(goodsData.stages.length!=0){
                    var stagesLength = goodsData.stages.length;
                    $('.stage_periods').html(goodsData.stages[stagesLength-1].instalmentAmount+'x'+goodsData.stages[stagesLength-1].periods+' 期');
                    $('#stages').show();
                    doStage(goodsData.stages);
                }
                $('#price_trend_box').css('display', 'none');
                $('#goodsName').html(goodsData.name);
                $('#goodsExplain').html(goodsData.goodsExplain);
                $('#memberPrice').html('￥' + goodsData.memberPrice);
                $('#code').html('商品编号：' + goodsData.code);
                 topHeight = $('.pull_title').offset().top;
                var goodsService = goodsData.goodsService;
                if (goodsService.length > 0) {
                    $('#goodsService').show();
                }
                for (var i = 0; i < goodsService.length; i++) {
                    $('<div class="potence"><img src="../phoneImg/petence_pigeon.png" alt=""><span>' + goodsService[i].name + '</span></div>').appendTo($('#goodsService'));
                    $('<li><div class="mui-clearfix">' +
                        '<div class="service_detail_img"><img src="' + goodsService[i].imgUrl + '" alt=""></div>' +
                        '<div class="service_fr">' +
                        '<span>' + goodsService[i].name + '</span><span>' + goodsService[i].details + '</span>' +
                        '</div></div></li>').appendTo($('#service_detail_box'));
                }
                //服务详情

                //评价
                $('#commentsCount').html('评价(' + goodsData.commentsCount + '' + ')');
                $('#commentsNum').html('评价(' + goodsData.commentsCount + '' + ')');
                var commentData = goodsData.commentsList;
                for (var k = 0; k < commentData.length; k++) {
                    $('#comment_title').after($('<div class="comment">\n' +
                        '<div class="comment-user mui-clearfix">\n' +
                        '<div class="user-img"><img src="../img/comment_h.jpg" alt="头像"></div>\n' +
                        '<div class="user-info">\n' +
                        '<span class="user-name">' + commentData[k].userName + '</span>\n' +
                        '</div>\n' +
                        '<div class="user-star" id="user-star">\n' +
                        '<span id="add_star2" class="add-star2"></span>\n' +
                        '<span id="del_star2" class="del-star2"></span>\n' +
                        '</div>\n' +
                        '</div>\n' +
                        '<div class="comment-detail">\n' + commentData[k].content +
                        '</div>\n' +
                        '<div class="comment_spe">' + commentData[k].propertiesName + '</div>\n' +
                        '</div>'))
                }
            }
        }
    })
}

function doStage(stages) {
    $('.stage_detail_box').empty();
    for(var i=0;i<stages.length;i++){
        $('<li class="mui-clearfix">\n' +
            '<div class="state_detail_img"><img class="stageSelect" src="../phoneImg/no_pigeon.jpg" alt=""></div>\n' +
            '<div class="state_fr">\n' +
            '<span>￥'+stages[i].instalmentAmount+'x'+stages[i].periods+' 期</span>\n' +
            '</div>\n' +
            '</li>').appendTo($('.stage_detail_box'))
    }
    mui('body').on('tap','.stageSelect',function () {
        if($(this).attr('src')=='../phoneImg/no_pigeon.jpg'){
            $(this).parent().parent().siblings().find('.stageSelect').attr('src','../phoneImg/no_pigeon.jpg')
            $(this).attr('src','../phoneImg/goods_pigeon.jpg')
        }
    })
}

var propertiesId = '';
var param;
var propertiesName;
var speLength = 0;

//获取规格
function doSpe() {
    //无规格商品
    if (!specification) {
        $('<div class="detail_count_title">' +
            '<span>数量</span>' +
            '<span class="choose_count">' +
            '<span class="decreace"></span' +
            '><input type="text"  class="count" style="width: 60px;" value="1"' +
            '><span class="add"></span>' +
            '</span>' +
            '</div>').insertBefore($('#appreciation_box'));
        detail();
    } else {
        //规格商品
        $.ajax({
            url: '/specificationC/getSpecification.json',
            dataType: 'json',
            data: {
                goodid: GetQueryString('goodsId'),
                companyCode:getItem('companyCode'),
            },
            type: 'post',
            success: function (data) {
                var speData = data.datas;
                speLength = speData.length;
                for (var i = 0; i < speData.length; i++) {
                    $('<div class="detail_small_box" id="detail_spe' + speData[i].id + '"></div>').insertBefore($('#appreciation_box'));
                    $('<div class="detail_title">' + speData[i].name + '</div>').appendTo($('#detail_spe' + speData[i].id + ''));
                    $('<div class="detail_spe mui-clearfix" id="detailOne_spe' + speData[i].id + '" bigId="'+speData[i].id+'"></div>').appendTo($('#detail_spe' + speData[i].id + ''));
                    for (var b = 0; b < speData[i].data.length; b++) {
                        $('<div class="spe-one" parent="' + speData[i].id + '" son="' + speData[i].data[b].id + '" id="' + speData[i].data[b].id + '">' + speData[i].data[b].content + '</div>').appendTo($('#detailOne_spe' + speData[i].id + ''));
                    }
                }
                $('<div class="detail_count_title">' +
                    '<span>数量</span>' +
                    '<span class="choose_count">' +
                    '<span class="decreace">-</span' +
                    '><input type="text" class="count"  value="1"' +
                    '><span class="add"></span>' +
                    '</span>' +
                    '</div>').insertBefore($('#appreciation_box'));

                //获取有效id
                $.ajax({
                    url:'/specificationContentC/getSpecificationContentid.json',
                    dataType:'json',
                    data:{
                        goodid:goodsId,
                        companyCode:getItem('companyCode'),
                    },
                    type:'post',
                    success:function (data) {
                        if(data.code==1){
                            param = data.datas[data.datas.length-1];
                            var delPAram = param.trim('{').trim('}');
                            var actParam = delPAram.split(',');
                            for(var g = 0;g<actParam.length;g++){
                                var actParam2 =actParam[g].split(':');
                                $('#'+actParam2[1]+'').addClass('spe_act');
                                $('#'+actParam2[1]+'').attr('ifAct','true');
                            }
                            doValid(delPAram);
                            $.ajax({
                                url: '/goodSpecificationC/getGoodSpecification.json',
                                dataType: 'json',
                                data: {
                                    goodid: GetQueryString('goodsId'),
                                    propertiesid: delPAram,
                                    companyCode:getItem('companyCode'),
                                },
                                type: 'post',
                                success: function (data) {
                                    //获取规格库存，图片
                                    if (data.code == 1) {
                                        $('#spe_img').attr('src', data.datas.image);
                                        $('.price').html('¥' + data.datas.memberPrice);
                                        propertiesId = data.datas.id;
                                        priceSpecificationId = data.datas.id;
                                        detail();
                                        doPrice();
                                        propertiesName = data.datas.propertiesName;
                                        if(data.datas.stages!=0){
                                            var stagesLength = data.datas.stages.length;
                                            $('.stage_periods').html(data.datas.stages[stagesLength-1].instalmentAmount+'x'+data.datas.stages[stagesLength-1].periods+' 期');
                                            $('#stages').show();
                                            doStage(data.datas.stages)
                                        }else{
                                            $('#stages').hide();
                                        }
                                        $('#marketprice').html('<span>市场价' + data.datas.maketPirce + '</span>');
                                        $('#memberprice').html('¥' + data.datas.memberPrice);
                                        //获取已选择字符串拼接，待测试
                                        var speStr = '';
                                        $('.spe_act').each(function () {
                                            speStr += $(this).html() + ', ';
                                        })
                                        speStr += '* ' + $('.count').val();
                                        $('#choose').html('已选');
                                        $('#choose_detail').html(propertiesName+'* ' + $('.count').val());
                                    }
                                    if(data.code==0){
                                        //thisDiv.find('.detail_spe .spe-one:nth-of-type(1)').removeClass('spe_act');
                                        //thisDiv.find('.detail_spe .spe-one:nth-of-type(1)').attr('ifAct', 'false');
                                    }
                                }
                            })
                        }
                    }
                })
                // $('.detail_spe').each(function () {
                //     var thisDiv = $(this);
                //     thisDiv.find('.spe-one:nth-of-type(1)').addClass('spe_act');
                //     thisDiv.find('.spe-one:nth-of-type(1)').attr('ifAct', 'true');
                //     var o = $("div[ifAct='true']");
                //     param = '';
                //     for (var i = 0; i < o.length; i++) {
                //         param += $(o.get(i)).attr('parent') + ':' + $(o.get(i)).attr('son');
                //         if (i != o.length - 1) {
                //             param += ','
                //         }
                //     }
                //
                // })
                //选择加入购物车
                $('.spe-one').click(function () {
                    var this2 = $(this);
                    //如果此规格包含虚线
                    if($(this).hasClass('spe_noChoose')){
                        this2.siblings().removeClass('spe_act').removeClass('spe_noChoose').addClass('spe_defalut');
                        this2.siblings().attr('ifAct', 'false');
                        this2.removeClass('spe_noChoose').removeClass('spe_defalut').addClass('spe_act');
                        this2.attr('ifAct', 'true');
                        this2.parent().parent().siblings().find('.spe-one').removeClass('spe_noChoose').removeClass('spe_act').addClass('spe_defalut');
                        this2.parent().parent().siblings().find('.spe-one').attr('ifAct', 'false');
                    }else{
                        this2.removeClass('spe_noChoose').removeClass('spe_defalut').addClass('spe_act');
                        this2.attr('ifAct', 'true');
                        this2.siblings().attr('ifAct', 'false');
                        this2.siblings().removeClass('spe_noChoose').removeClass('spe_act').addClass('spe_defalut');
                        this2.parent().parent().siblings().find('.spe-one').each(function () {
                            if($(this).hasClass('spe_noChoose')){
                                $(this).removeClass('spe_noChoose').addClass('spe_defalut');
                            }
                        })
                    }

                    var o2 = $("div[ifAct='true']");
                    var param2 = '';
                    for (var l = 0; l < o2.length; l++) {
                        param2 += $(o2.get(l)).attr('parent') + ':' + $(o2.get(l)).attr('son');
                        if (l != o2.length - 1) {
                            param2 += ','
                        }
                    }
                    doValid(param2);

                    if (speLength == 2) {
                        if ($('div[ifact=true]').length == 2) {
                            dospeDetail();
                        }
                    } else if (speLength == 1) {
                        dospeDetail();
                    }
                    else if (speLength == 3) {
                        if ($('div[ifact=true]').length == 3) {
                            dospeDetail();
                        }
                    }

                })

                function dospeDetail() {
                    var o = $("div[ifAct='true']");
                    param = '';
                    for (var i = 0; i < o.length; i++) {
                        param += $(o.get(i)).attr('parent') + ':' + $(o.get(i)).attr('son');
                        if (i != o.length - 1) {
                            param += ','
                        }
                    }
                    $.ajax({
                        url: '/goodSpecificationC/getGoodSpecification.json',
                        dataType: 'json',
                        data: {
                            goodid: GetQueryString('goodsId'),
                            propertiesid: param,
                            companyCode:getItem('companyCode'),
                        },
                        type: 'post',
                        beforeSend: function () {
                            if (speLength == 2) {
                                if ($('div[ifact=true]').length == 2) {
                                    $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
                                }
                            } else if (speLength == 1) {
                                $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
                            }
                            else if (speLength == 3) {
                                if ($('div[ifact=true]').length == 3) {
                                    $('<div class="loading2"><span class="mui-spinner"></span></div>').appendTo($('body'));
                                }
                            }
                        },
                        success: function (data) {
                            //获取规格库存，图片
                            if (data.code == 1) {
                                $('.loading2').hide();
                                $('#spe_img').attr('src', data.datas.image);
                                $('.price').html('¥' + data.datas.memberPrice);
                                propertiesId = data.datas.id;
                                priceSpecificationId = data.datas.id;
                                detail();
                                doPrice();
                                propertiesName = data.datas.propertiesName;
                                if(data.datas.stages!=0){
                                    var stagesLength = data.datas.stages.length;
                                    $('.stage_periods').html(data.datas.stages[stagesLength-1].instalmentAmount+'x'+data.datas.stages[stagesLength-1].periods+' 期');
                                    $('#stages').show();
                                    doStage(data.datas.stages)
                                }else{
                                    $('#stages').hide();
                                }
                                $('#marketprice').html('<span>市场价' + data.datas.maketPirce + '</span>');
                                $('#memberprice').html('¥' + data.datas.memberPrice);
                            }
                            if(data.code==0){
                                $('.loading2').hide();
                                if(speLength==2){
                                    if ($('div[ifact=true]').length == 2) {
                                        mui.toast(data.msg);
                                        return;
                                    }
                                }
                                if(speLength==3){
                                    if ($('div[ifact=true]').length == 3) {
                                        mui.toast(data.msg);
                                        return;
                                    }
                                }
                                if(speLength==1){
                                    mui.toast(data.msg);
                                    return;
                                }
                            }
                        }
                    })
                }
            }
        })
    }
}

function doValid(validId) {
    //获取无效id
    $.ajax({
        url:'/goodSpecificationC/getGoodSpecificationContent.json',
        dataType:'json',
        data:{
            gooid:goodsId,
            propertiesid:validId,
            companyCode:getItem('companyCode'),
        },
        type:'post',
        success:function (data) {
            for(var d = 0;d<data.datas.length;d++){
                var e = data.datas[d];
                var f = document.getElementById(e)
                if($(f).length>0)
                {
                    $(f).removeClass('spe_defalut').removeClass('spe_act').addClass('spe_noChoose');
                }
                else
                {

                }
            }
        }
    })
}

var addServiceId = [];

//增值服务
function doService() {
    $.ajax({
        url: '/ddmGoodsC/getGoodsValueAddedServices.json',
        dataType: 'json',
        data: {
            id: goodsId,
            companyCode:getItem('companyCode'),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                var serviceData = data.datas;
                for (var i = 0; i < serviceData.length; i++) {
                    $('<li class="mui-clearfix">' +
                        '<span class="appreciation-one" addAct="false" addId="' + serviceData[i].id + '"><span class="appreciation_name">' + serviceData[i].name + ' </span>' +
                        '<span class="appreciation_price">￥' + serviceData[i].price + '</span></span>' +
                        '<span class="appreciation_more" url="' + serviceData[i].detailsUrl + '" id="' + serviceData[i].id + '">查看详情</span>' +
                        '</li>').appendTo($('.appreciation_detail'))
                }

                //选择增值服务
                $('.appreciation-one').click(function () {
                    if ($(this).attr('addAct') == 'true') {
                        $(this).removeClass('addAct');
                        $(this).find('span:nth-child(1)').removeClass('appreciation_name_act');
                        $(this).find('span:nth-child(2)').removeClass('appreciation_price_act');
                        $(this).attr('addAct', 'false');
                    } else {
                        $(this).addClass('addAct');
                        $(this).find('span:nth-child(1)').addClass('appreciation_name_act');
                        $(this).find('span:nth-child(2)').addClass('appreciation_price_act');
                        $(this).attr('addAct', 'true');
                    }

                })
            }
        }
    })
    mui('body').on('tap', '.appreciation_more', function () {
        window.location.href = $(this).attr('url')
    })
}

var ifClickCart = 'false';
var ifClickBuy = 'false';

$(document).ready(function () {
    //添加
    var count = 1;
    $(document).on('click', '.add', function () {
        count++;
        if (count > 1) {
            $('.decrease').css('color', '#49c9bb');
        }
        $('.count').val(count);
    })
    //减少
    $(document).on('click', '.decreace', function () {
        count--;
        if (count < 1) {
            count = 1;
            $('.decreace').css('color', '#bfbcc0');
        }
        if (count > 1) {
            $('.decreace').css('color', '#49c9bb');
        }
        $('.count').val(count);
    })
    //输入产品数量
    $("body").on('change', '.count', function () {
        //判断输入数量是否为空或小于1
        if ($('.count').val() == '' || $('.count').val() == NaN || $('.count').val() < 1 || $('.count').val() == null || $('.count').val() == undefined) {
            $('.count').val(1);
        }
        count = parseInt($('.count').val());
        if (count > 1) {
            $('.decrease').css('color', '#49c9bb');
        }
    })
})

//确定
$('.spe_certain').click(function () {
    //增值服务
    $(".addAct").each(function () {
        var addId = $(this).attr('addId');
        addServiceId.push(addId);
    })


    if (ifClickCart == 'true') {
        addServiceId = addServiceId.toString();
        addCart();
        return;
    }
    if (ifClickBuy == 'true') {
        if (addServiceId == null || addServiceId == undefined || addServiceId == ""||addServiceId == '""') {
            addServiceId = '"' + '"';
        } else {
            if (addServiceId.length == 1) {
                addServiceId = addServiceId.toString();
                addServiceId = '"' + addServiceId + '"'
            } else {
                var firstAddId = addServiceId[0];
                var lastAddId = addServiceId[addServiceId.length - 1];
                addServiceId.splice(0, 1, '"' + firstAddId);
                addServiceId.splice(-1, 1, lastAddId + '"');
                addServiceId = addServiceId.toString();
            }
        }
        buy();
        return;
    }


    //获取已选择字符串拼接
    var speStr = '';
    $('.spe_act').each(function () {
        speStr += $(this).html() + ', ';
    })
    speStr += '* ' + $('.count').val();
    $('.specification_box').hide();
    $('.float-box').show();
    $('.choose-sku').html('<span class="choose">已选择</span><span class="choose-yet">' + speStr + '</span>');

})

//点击加入购物车
$('.add-cart').click(function () {
    ifClickCart = 'true';
    ifClickBuy = 'false';
    getSpe();
})

function getSpe() {
    if (propertiesId == undefined || propertiesId == null || propertiesId == "") {
        document.body.scrollTop = document.documentElement.scrollTop = 0;
        $('.specification_box').show();
        $('.specification_box').css({'opacity':'1','top':'0','height':'100%','visibility':'visible'})
        $('body,html,.mui-content').css({'height': '100%', 'overflow': 'hidden'});
        $('.float-box').hide();
    } else {
        if(ifChoose==0){
            document.body.scrollTop = document.documentElement.scrollTop = 0;
            $('.specification_box').show();
            $('.specification_box').css({'opacity':'1','top':'0','height':'100%','visibility':'visible'})
            $('body,html,.mui-content').css({'height': '100%', 'overflow': 'hidden'});
            $('.float-box').hide();
            return;
        }
        if (ifClickCart == 'true') {
            addCart();
            return;
        }
        if (ifClickBuy == 'true') {
            buy();
            return;
        }
    }
}


//加入购物车
function addCart() {
    $.ajax({
        url: '/ShoppingCartC/addUserShoppingCart.json',
        dataType: 'json',
        data: {
            goodsId: goodsId,
            count: $('.count').val(),
            specificationId: propertiesId,
            token: getItem('token'),
            valueAddedServicesIds: addServiceId,
            companyCode:getItem('companyCode'),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                //获取已选择字符串拼接，待测试
                var speStr = '';
                $('.spe_act').each(function () {
                    speStr += $(this).html() + ', ';
                })
                speStr += '* ' + $('.count').val();
                $('.specification_box').hide();
                $('.float-box').show();
                mui.toast('加入购物车成功');
                propertiesId = '';
                $('.spe-one').removeClass('spe_act');
                $('.spe-one').attr('ifact', 'false');
                $('#choose').html('已选');
                $('#choose_detail').html(speStr);
            }
            if (data.code == 0) {
                mui.toast(data.msg);
                propertiesId = '';
                return;
            }
            if (data.code == -1) {
                window.location.href = "login.html";
            }
        }
    })
}

//立即购买
$('.buy').click(function () {
    ifClickBuy = 'true';
    ifClickCart = 'false';
    getSpe();
})

function buy() {
    if (specification) {
        if (propertiesId == null || propertiesId == undefined || propertiesId == "") {
            mui.toast('规格id获取失败，请重试');
            return;
        }
    } else {
        if (propertiesId == null || propertiesId == undefined || propertiesId == "") {
            propertiesId = '"' + '"';
        }
    }
    if(addServiceId==''){
        addServiceId='"'+'"';
    }
    var orderInfor = '[{goodId:' + goodsId + ',num:' + $('.count').val() + ',goodSpecificationId:' + propertiesId + ',addService:' + addServiceId + '}]';
    removeItem('deliveryType');
    removeItem('payType');
    removeItem('addressId');
    window.location.href = "confirmOrder.html?type=1&orderInfor=" + orderInfor
}


//标题点击
document.getElementById('detail').addEventListener('tap',function () {
    ifComment = 'false';
    ifSlide = 'false';
    $('#goodsBox1,#detailBox').show();
    $('#commentBox').hide();
    $('#detail').addClass('act');
    $('#detail').find('span').show();
    $('#goods,#comment').removeClass('act');
    $('#goods,#comment').children().hide();
    mui('.mui-scroll-wrapper2').scroll().reLayout();//重新计算布局值，最大滚动的高度等等
    var y = 0;
    var current_top = mui('.mui-scroll-wrapper2').scroll().y;
    y = $('#detailBox').offset().top; //计算位置
    y = parseInt(current_top - y);
    if (y > 0)
        y = -y;
    mui('#refreshContainer').scroll().scrollTo(0, parseInt(y+44) , 0);
    //mui('#refreshContainer').scroll().scrollTo(-($('#detailBox').offset().top),0);
    //scroll2($('#detailBox').offset().top);
    ifSlide = 'true';
})
document.getElementById('goods').addEventListener('tap',function () {
    ifComment = 'false';
    ifSlide = 'false';
    $('#goodsBox1,#detailBox').show();
    $('#commentBox').hide();
    $('#goods').addClass('act');
    $('#goods').find('span').show();
    $('#detail,#comment').removeClass('act');
    $('#detail,#comment').children().hide();
    mui('#refreshContainer').scroll().scrollTo(0, 0 , 0);
    ifSlide = 'true';
})
document.getElementById('comment').addEventListener('tap',function () {
    ifComment = 'true';
    ifSlide = 'false';
    $('#goodsBox1,#detailBox').hide();
    $('#commentBox').show();
    $('#comment').addClass('act');
    $('#comment').find('span').show();
    $('#detail,#goods').removeClass('act');
    $('#detail,#goods').children().hide();
    mui('#refreshContainer').scroll().scrollTo(0, 0 , 0);
})

function scroll2(e) {
    mui.scrollTo(e,200);
}

//更多按钮
$('#share2,#share,.more').click(function () {
    //分享到朋友圈
    if (is_weixn()) {
        mui.alert('请点击右上角分享')
    } else {
        mui.alert('请在微信中打开')
    }
})

var uip = document.getElementById("topPopover");
uip.style.position = "absolute";
$(".mui-backdrop").click(function () {
    $("#topPopover").hide();
    $(".mui-backdrop").hide();
});
mui('body').on('tap', '.mui-table-view-cell a', function () {
    document.location.href = this.href;
});

//购物车跳转
document.getElementById('cart').addEventListener('tap', function () {
    window.location.href = "cart.html?ifGoods=1";
})

//分期盒子
document.getElementById('stages').addEventListener('tap', function () {
    showBox('.stage_float_box', 200);
    document.getElementById('close_stage').addEventListener('tap', function () {
        $('.stage_float_box').hide();
        $('.float-box').show();
    })
    document.getElementById('stages_transaction').addEventListener('tap', function () {
        //hideBox('.stage_float_box', 100);
        window.location.href="shop-list2.html"
    })
})

//规格盒子
document.getElementById('choose_box').addEventListener('tap', function () {
    $('#mui-scroll-wrapper').css('top',liHeight+'px');
    document.body.scrollTop = document.documentElement.scrollTop = 0;
    $('.specification_box').show();
    $('.specification_box').css({'opacity':'1','top':'0','height':'100%','visibility':'visible'})
    $('body,html,.mui-content').css({'height': '100%', 'overflow': 'hidden'});
    $('.float-box').hide();
})


//规格盒子关闭
document.getElementById('colse_spe').addEventListener('tap', function () {
    //hideBox('.specification_box', 100);
    //$('#mui-scroll').css('transform','translate3d(0px, 0px, 0px) translateZ(0px)');
    $('.specification_box').hide();
    //$('.specification_box').css({'opacity':'0','top':'100%','height':'0','visibility':'hidden'})
    //$('body,html,.mui-content').css({'height': 'auto', 'overflow': 'auto'});
    $('.float-box').show();
})

//地址盒子
// document.getElementById('send_box').addEventListener('tap', function () {
//     showBox('.goods_address_box', 200);
//     document.getElementById('colse_address').addEventListener('tap', function () {
//         hideBox('.goods_address_box', 100);
//     })
// })

//价格趋势
document.getElementById('trend').addEventListener('tap', function () {
    showBox('.price_trend_box', 200);
    document.getElementById('close_price').addEventListener('tap', function () {
        $('.price_trend_box').hide();
        $('.float-box').show();
    })
})

//服务说明
document.getElementById('goodsService').addEventListener('tap', function () {
    showBox('.service_explain_box', 200);
    document.getElementById('close_service').addEventListener('tap', function () {
        //hideBox('.service_explain_box', 100);
        $('.service_explain_box').hide();
        $('.float-box').show();
    })
})

//评价更多
document.getElementById('comment_title').addEventListener('tap', function () {
    ifSlide = 'false';
    $('#goodsBox1,#detailBox,.pull_title').hide();
    $('#commentBox').show();
    $('#comment').addClass('act');
    $('#comment').find('span').show();
    $('#detail,#goods').removeClass('act');
    $('#detail,#goods').children().hide();
    ifSlide = 'true';
})

//添加收藏
document.getElementById('collection').addEventListener('tap', function () {
    if ($('#collection_img').attr('src') == '../phoneImg/collection.png') {
        $.ajax({
            url: '/collectionsC/addCollections.json',
            dataType: 'json',
            data: {
                goodsId: goodsId,
                token: token,
                companyCode:getItem('companyCode'),
            },
            type: 'post',
            success: function (data) {
                if (data.code == 1) {
                    $('#collection_img').attr('src', '../phoneImg/collection_act.png')
                    $('#collText').html('已收藏');
                    collectionsId = data.datas.collectionsId;
                }
                if (data.code == -1) {
                    window.location.href = "login.html"
                }
                if (data.code == 0) {
                    mui.toast(data.msg);
                }
            }
        })
    } else {
        $.ajax({
            url: '/collectionsC/delCollections.json',
            dataType: 'json',
            data: {
                idStr: collectionsId,
                token: token,
                companyCode:getItem('companyCode'),
            },
            type: 'post',
            success: function (data) {
                if (data.code == 1) {
                    $('#collection_img').attr('src', '../phoneImg/collection.png')
                    $('#collText').html('收藏');
                }
                if (data.code == -1) {
                    window.location.href = "login.html"
                }
                if (data.code == 0) {
                    mui.toast(data.msg);
                }
            }
        })
    }
})

var commentStateValue = '1';

//所有评价
function doComment() {
    $.ajax({
        url: '/commentsC/commentsSumdatas.json',
        dataType: 'json',
        data: {
            goodsId: goodsId,
            companyCode:getItem('companyCode'),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                var commentData = data.datas;
                for (var i = 0; i < commentData.length; i++) {
                    $('<div class="swiper-slide" id="' + commentData[i].commentsPropertyValue +'" stateValue= "' + commentData[i].commentsPropertyValue +'">' +
                        '<span>' + commentData[i].commentsProperty + '<b>' + commentData[i].count + '</b></span></div>').appendTo($('#allComment_title_box'))
                }
                $('#allComment_title_box .swiper-slide:nth-child(1)').addClass('active')
                var mySwiper = new Swiper('#topNav', {
                    freeMode: true,
                    freeModeMomentumRatio: 0.5,
                    slidesPerView: 'auto',

                });
                //滑动评价
                swiperWidth = mySwiper.container[0].clientWidth
                maxTranslate = mySwiper.maxTranslate();
                maxWidth = -maxTranslate + swiperWidth / 2

                $(".swiper-container").on('touchstart', function (e) {
                    e.preventDefault()
                })

                mySwiper.on('tap', function (swiper, e) {
                    //slide = swiper.slides[swiper.clickedIndex]
                    //slideLeft = slide.offsetLeft
                    //slideWidth = slide.clientWidth
                    //slideCenter = slideLeft + slideWidth / 2
                    // 被点击slide的中心点
                    //mySwiper.setWrapperTransition(300)
                    //if (slideCenter < swiperWidth / 2) {
                    //mySwiper.setWrapperTranslate(0)
                    //} else if (slideCenter > maxWidth) {
                    //mySwiper.setWrapperTranslate(maxTranslate)
                    //} else {
                    //nowTlanslate = slideCenter - swiperWidth / 2
                    //mySwiper.setWrapperTranslate(-nowTlanslate)
                    //}
                    $("#topNav  .active").removeClass('active')

                    $("#topNav .swiper-slide").eq(swiper.clickedIndex).addClass('active');
                    commentStateValue = $("#topNav .swiper-slide").eq(swiper.clickedIndex).attr('stateValue');
                })
            }
        }
    })
}

var num1 = 0;
var page =0;
function doCommentList() {
    page++;
    $.ajax({
        url: '/commentsC/getCommentsList.json',
        dataType: 'json',
        data: {
            commentsPropertyValue: commentStateValue,
            goodsId: goodsId,
            companyCode:getItem('companyCode'),
        },
        type: 'post',
        success: function (data) {
            if (data.code == 1) {
                $('#commentNum').html("评价（"+data.recordsTotal+"）");
                $('#comment-box').empty();
                var initData = data.datas;
                if(page==1){
                    if(data.datas.length==0){
                        $('<div class="kong"><img src="../phoneImg/kong.png" alt="暂无数据"></div>').appendTo($('#comment-box'))
                    }
                }
                for (var i = 0; i < initData.length; i++) {
                    var dataAutor = initData[i].avotorr;
                    var shopReply = initData[i].replyMessage;
                    var replyMessage;
                    var autor;
                    if (dataAutor == "") {
                        autor = '../phoneImg/gray_placeholder.png';
                    } else {
                        autor = dataAutor;
                    }
                    //商家回复
                    if (shopReply == "") {
                        replyMessage = '';
                    } else {
                        replyMessage = '<div class="reply-sanjiao"></div>\n' +
                            '<div class="reply-box"><span>商家回复：</span>' + shopReply + '</div>'
                    }

                    $('<div class="comment">\n' +
                        '<div class="comment-user mui-clearfix">\n' +
                        '<div class="user-img"><img src="' + autor + '" alt="头像"></div>\n' +
                        '<div class="user-info">\n' +
                        '<span class="user-name">' + initData[i].userName + '</span>\n' +
                        '</div>\n' +
                        '<div class="user-star"><span class="add-star2"></span>\n' +
                        '<span class="del-star2"></span></div>\n' +
                        '</div>\n' +
                        '<div class="comment-detail">' + initData[i].content + '</div>\n' +
                        '<div class="comment-img-box mui-clearfix" id="comment' + initData[i].id + '">\n' +
                        '</div><div class="comment_spe">' + initData[i].propertiesName + '</div>' + replyMessage +
                        '</div>').appendTo($('#comment-box'))

                    var commentImg = initData[i].imgUrl.split(',');
                    var imgWidth = $('body').width() * 0.86 * 0.32 - 30
                    $('.comment-img-box img').css('height', imgWidth);
                    for (var b = 0; b < commentImg.length-1; b++) {
                        $('<div><img data-preview-src="" data-preview-group="' + initData[i].id + '" src="' + commentImg[b] + '" alt=""></div>').appendTo($('#comment' + initData[i].id + ''))
                    }
                    if (commentImg.length > 3) {
                        //$('.comment-box .comment .comment-img-box div:nth-child(3)').css('position', 'relative');
                        //$('<span class="comment-img-number">' + (commentImg.length-1) + '</span>').appendTo($('#comment' + initData[i].id + ' div:last-child'));
                    }
                }

                num1 = data.datas.length;
            }
        }
    })
    return num1;
}

function guess() {
    $.ajax({
        url:'/ddmGoodsC/guessYouLiveGoods.json',
        dataType:'json',
        data:{
            token:getItem('token'),
            companyCode:getItem('companyCode'),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                if(data.datas.length>6){
                    mui('.mui-slider').slider().setStopped(false);
                    for(var i=0;i<6;i++){
                        $('<a href="goods.html?goodsId='+data.datas[i].id+'">\n' +
                            '<div class="guess_goods">\n' +
                            '<img src="'+data.datas[i].mainImg+'" alt="">\n' +
                            '<p class="guess_goods_title">'+data.datas[i].name+'</p>\n' +
                            '<p class="guess_price">￥'+data.datas[i].memberPrice+'</p>\n' +
                            '</div></a>').appendTo($('#guess1'))
                    }
                    for(var h=6;h<data.datas.length;h++){
                        $('<a href="goods.html?goodsId='+data.datas[h].id+'">\n' +
                            '<div class="guess_goods">\n' +
                            '<img src="'+data.datas[h].mainImg+'" alt="">\n' +
                            '<p class="guess_goods_title">'+data.datas[h].name+'</p>\n' +
                            '<p class="guess_price">￥'+data.datas[h].memberPrice+'</p>\n' +
                            '</div></a>').appendTo($('#guess2'))
                    }
                    $('#guess2,#guess_slide2').show();
                    $('#guess_slide1').addClass('mui-active');
                }else{
                    mui('.mui-slider').slider().setStopped(true);
                    for(var i=0;i<data.datas.length;i++){
                        $('<a href="goods.html?goodsId='+data.datas[i].id+'">\n' +
                            '<div class="guess_goods">\n' +
                            '<img src="'+data.datas[i].mainImg+'" alt="">\n' +
                            '<p class="guess_goods_title">'+data.datas[i].name+'</p>\n' +
                            '<p class="guess_price">￥'+data.datas[i].memberPrice+'</p>\n' +
                            '</div></a>').appendTo($('#guess1'))
                    }
                    $('#guess2,#guess_slide2').hide();
                }

                var guessWidth = $('body').width()*0.31*0.93;
                $('.guess_goods img').css('height',guessWidth+'px');
                mui('body').on('tap','.mui-slider-item a',function () {
                    window.location.href=$(this).attr('href');
                })
                $(document).ready(function(){
                    $(".guess_goods>img").on("load",function(){
                        topHeight = $('.pull_title').offset().top;
                        return;
                    });
                });
            }
        }
    })
}


function detail() {
    $('#detailBox2,#detailBox3').empty();
    $.ajax({
        url:'/ddmGoodsC/portalDetails2.json',
        dataType:'json',
        data:{
            id:goodsId,
            goodSpecificationId:propertiesId,
            companyCode:getItem('companyCode'),
        },
        type:'post',
        success:function (data) {
            if(data.code==1){
                $(data.datas.parameter).appendTo($('#detailBox2'));
                $(data.datas.safeguard).appendTo($('#detailBox3'));
            }
        }
    })
}

//规格参数
mui('body').on('tap','.parameter li',function () {
    $(this).addClass('par-active');
    $(this).siblings().removeClass('par-active');
    var showDiv = $(this).attr('showDiv');
    $('#'+showDiv+'').show();
    $('#'+showDiv+'').siblings().hide();
})

//分享
var ticket;
var timer;
var wxSha1;
$(function () {
    $.ajax({
        url:'/shareC/getAccessToken.json',
        dataType:'json',
        data:{
            companyCode:getItem('companyCode'),
        },
        type:'post',
        success:function (data) {
            ticket = data.datas;
            timer = Date.parse(new Date());
            timer = timer / 1000;
            var WXsignature = 'jsapi_ticket=' + ticket + '&noncestr=Wm3WZYTPz0wzccnW&timestamp=' + timer + '&url=' + location.href.split('#')[0]
            wxSha1 = hex_sha1(WXsignature);
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                appId: 'wxcae7693294154eb4', // 必填，公众号的唯一标识
                timestamp: timer, // 必填，生成签名的时间戳
                nonceStr: 'Wm3WZYTPz0wzccnW', // 必填，生成签名的随机串
                signature: wxSha1,// 必填，签名，见附录1
                jsApiList: ['checkJsApi','onMenuShareTimeline','onMenuShareAppMessage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
            });

            wx.ready(function(){
                // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，
                wx.checkJsApi({
                    jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'], // 需要检测的JS接口列表，所有JS接口列表见附录2,
                    success: function(res) {
                        // 以键值对的形式返回，可用的api值true，不可用为false
                        // 如：{"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
                    },
                    fail:function () {
                        mui.alert('您的微信版本过低，暂不支持分享，请升级微信')
                    }
                });

                //分享给朋友
                wx.onMenuShareAppMessage({
                    title: '叮当一响，手机到家', // 分享标题
                    desc: '购物不再满街走，叮当卖场全都有', // 分享描述
                    link: 'http://ddt.chinaddcat.com/m/phoneHtml/goods.html?goodsId='+goodsId+'&userId='+userId+'&companyCode='+getItem('companyCode'), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: 'http://ddt.chinaddcat.com/m/phoneImg/share_logo.jpg', // 分享图标
                    type: '', // 分享类型,music、video或link，不填默认为link
                    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                    success: function () {
                        mui.toast('分享成功');
                        window.location.href='http://ddt.chinaddcat.com/m/phoneHtml/goods.html?goodsId='+goodsId+'&userId='+userId+'&companyCode='+getItem('companyCode');
                    },
                    cancel: function () {
                        mui.toast('您取消了分享')
                        // 用户取消分享后执行的回调函数
                    }
                });

                //分享到朋友圈
                wx.onMenuShareTimeline({
                    title: '叮当一响，手机到家', // 分享标题
                    desc: '购物不再满街走，叮当卖场全都有', // 分享描述
                    link: 'http://ddt.chinaddcat.com/m/phoneHtml/goods.html?goodsId='+goodsId+'&userId='+userId+'&companyCode='+getItem('companyCode'), // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                    imgUrl: 'http://ddt.chinaddcat.com/m/phoneImg/share_logo.jpg', // 分享图标
                    success: function () {
                        mui.toast('分享成功');
                        $.ajax({
                            url:'/user/UpdateUserIntegral.json',
                            dataType:'json',
                            data:{
                                token:getItem('token'),
                                companyCode:getItem('companyCode'),
                            },
                            success:function(data){
                                mui.toast('分享成功');
                                window.location.href='http://ddt.chinaddcat.com/m/phoneHtml/goods.html?goodsId='+goodsId+'&userId='+userId;
                            }
                        })
                    },
                    cancel: function () {
                        mui.toast('您取消了分享')
                        // 用户取消分享后执行的回调函数
                    }
                });
            });
        }
    })
})

function getScrollTop() {
    //滚动条在Y轴上的滚动距离
    var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
    if (document.body) {
        bodyScrollTop = document.body.scrollTop;
    }
    if (document.documentElement) {
        documentScrollTop = document.documentElement.scrollTop;
    }
    scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
    return scrollTop;
}

//浏览器视口的高度
function getWindowHeight() {
    var windowHeight = 0;
    if (document.compatMode == "CSS1Compat") {
        windowHeight = document.documentElement.clientHeight;
    } else {
        windowHeight = document.body.clientHeight;
    }
    return windowHeight;
}

//文档的总高度
function getScrollHeight() {
    var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
    if (document.body) {
        bodyScrollHeight = document.body.scrollHeight;
    }
    if (document.documentElement) {
        documentScrollHeight = document.documentElement.scrollHeight;
    }
    scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
    return scrollHeight;
}
// $(window).on("scroll", function(){
//     //函数内判断，距离底部50px的时候则进行数据加载
//     if(ifSlide=='true'){
//         if(ifComment=='false'){
//             var toTopHeight = (document.documentElement.scrollTop || 0) + (document.body.scrollTop || 0);
//             if(toTopHeight+44>topHeight){
//                 $('#detail').addClass('act');
//                 $('#detail').find('span').show();
//                 $('#goods,#comment').removeClass('act');
//                 $('#goods,#comment').children().hide();
//             }else{
//                 $('#goods').addClass('act');
//                 $('#goods').find('span').show();
//                 $('#detail,#comment').removeClass('act');
//                 $('#detail,#comment').children().hide();
//             }
//         }
//     }
// });
var scroll = mui('.mui-scroll-wrapper2').scroll();
document.querySelector('.mui-scroll-wrapper2' ).addEventListener('scroll', function (e ) {
    var current_top = mui('.mui-scroll-wrapper2').scroll().y;
    var y = $('#detailBox').offset().top; //计算位置
    y=-y;
    if(ifSlide=='true'){
        if(ifComment=='false'){
            if(current_top<y){
                $('#detail').addClass('act');
                $('#detail').find('span').show();
                $('#goods,#comment').removeClass('act');
                $('#goods,#comment').children().hide();
            }else{
                $('#goods').addClass('act');
                $('#goods').find('span').show();
                $('#detail,#comment').removeClass('act');
                $('#detail,#comment').children().hide();
            }
        }
    }
})

var isIos = 0,
    isAnd = 0;

$(function () {
    //ios
    setupWebViewJavascriptBridge(function(bridge) {
        /* Initialize your app here */
        bridge.callHandler('getDevice', function(responseData) {
            isIos = 1;
        })
    })

})
//Android
function isAndroid() {
    isAnd = 1;
}

$('.link-qq').click(function () {
    if($('#QR-code').attr('src')==""||$('#QR-code').attr('src')==undefined||$('#QR-code').attr('src')==null){
        $.ajax({
            url:'/keFuC/getOne.json',
            dataType:'json',
            type:'post',
            data:{
                companyCode:getItem('companyCode')
            },
            success:function (data) {
                if(data.code==1){
                    $('#wxNum').html('微信号：'+data.datas.weChatNumber);
                    $('#QR-code').attr('src',data.datas.weChatCode);
                }
            }
        })
    }

    $('.QR-code').show();
    //window.location.href = "http://wpa.b.qq.com/cgi/wpa.php?ln=1&key=XzkzODE5MzgwMF80Njk1NzRfNDAwNjAxNjYwNl8yXw"
    document.getElementById('close').addEventListener('tap',function () {
        $('.QR-code').hide();
    })
})

mui('#mui-scroll-wrapper').scroll({
    deceleration: 0.0006, //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
});

mui('.mui-scroll-wrapper2').scroll({
    deceleration: 0.1, //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
    indicators: false
});

// mui('#top2').on('tap','a',function () {
//     window.location.href=$(this).attr('href');
//     //
//     // if (window.location.hash !== "") {
//     //     window.location.hash = "";
//     // }
//     // history.replaceState(null,'',location.pathname+location.search);
//     // scroll2($('#detailBox').offset().top)
//     return false;
// })

// document.getElementById('refreshContainer').addEventListener("swiperight",function(){
//     history.back();
// });